package com.op.teachingliteapp.sender.runnable;

import android.content.Context;
import android.os.Looper;
import com.op.teachingliteapp.sender.handler.SendCommandHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Created by Genji on 2015/5/19.
 */
public class SendCommandRunnable implements Runnable{
    private  int port;
    private String ip;
    private Context context;
    private  String commandString;
    public SendCommandRunnable(int port, String ip, Context context, String commandString) {
        this.port = port;
        this.ip = ip;
        this.context = context;
        this.commandString = commandString;
    }


    @Override
    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                    socketChannel.pipeline().addLast(new StringDecoder());

                    socketChannel.pipeline().addLast(new SendCommandHandler(context,commandString));
                }
            });
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();

        }
        finally {
            Looper.prepare();
            group.shutdownGracefully();
            Looper.loop();

        }


    }
    }

